<?php

namespace app\controllers;

use Yii;
use app\tools\Re;
use app\models\User;
use app\models\Good;
use app\models\Address;
use app\models\OrderInfo;
use app\models\OrderInfoGood;
use app\models\OrderInfoGoodEvaluate;
use app\models\ShoppingCart;

class OrderController extends BaseController
{
  public $state_arr = ['待付款', '待发货', '待收货', '售后中', '已完成', '退款中', '退款成功', '退款失败', '已取消'];

  //下单
	public function actionPlace() {
    //good_info[{"good_id":2,"num":2,"good_price":245.00,"shopping_cart_id":1}]
    $openid = Yii::$app->request->post('openid', '');
    $good_info = Yii::$app->request->post('good_info', '');
    $money = Yii::$app->request->post('money', 0);
		$pay_type = Yii::$app->request->post('pay_type', 1);
    $address_id = Yii::$app->request->post('address_id', 0);
    $remark = Yii::$app->request->post('remark', '');
    $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
    if (!$user_info) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }
		$address = Address::findOne($address_id);
		if (empty($address)) {
			return Re::data(null, '地址信息读取失败', Re::ERROR);
    }

    $order = new OrderInfo();
    $order->user_id = $user_info->id;
    $order->order_type = 1;
    $order->order_sn = time().rand(1000,9999);
    $order->money_origin = $money;
    $order->money_discount = 0;
    $order->money = $money;
    $order->pay_type = $pay_type;
    $order->remark = $remark;
    $order->address_id = $address_id;
    $order->created_at = time();
    if (!$order->save()) {
      return Re::data(null, $order->showErrors(), Re::ERROR);
    }
    foreach ($good_info as $v) {
      $good = Good::findOne($v->good_id);
      if (empty($good)) {
        return '商品信息读取失败';
      }
      if ($good->store < $v->num) {
        return '商品库存不足，无法下单';
      }
      //存储商品信息
      $order_good = new OrderInfoGood();
      $order_good->order_id = $order->id;
      $order_good->good_id = $v->good_id;
      $order_good->price = $v->good_price;
      $order_good->num = $v->num;
      if (!$order_good->save()) {
        return $order_good->showErrors();
      }
      $good->store -= $v->num;
      $good->save();
      if ($v->shopping_cart_id) {
        $shopping_cart = ShoppingCart::find()->where(['id' => $v->shopping_cart_id, 'user_id' => $user_info->id])->one();
        if ($shopping_cart) {
          $shopping_cart->delete();
        }
      }
    }
    return Re::data();
	}

  //各状态订单数量统计
  public function actionOrderCount(){
    $openid = Yii::$app->request->post('openid', '');
    $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
    if (!$user_info) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }

    $order_count_dzf = OrderInfo::find()->where(['user_id' => $user_info->id, 'order_type' => 1, 'state' => 0])->count();
    $order_count_dfh = OrderInfo::find()->where(['user_id' => $user_info->id, 'order_type' => 1, 'state' => 1])->count();
    $order_count_dsh = OrderInfo::find()->where(['user_id' => $user_info->id, 'order_type' => 1, 'state' => 2])->count();
    $order_count_shz = OrderInfo::find()->where(['user_id' => $user_info->id, 'order_type' => 1, 'state' => 3])->count();
    $order_count_wc = OrderInfo::find()->where(['user_id' => $user_info->id, 'order_type' => 1, 'state' => 4])->count();
    $order_count_tkz = OrderInfo::find()->where(['user_id' => $user_info->id, 'order_type' => 1, 'state' => 5])->count();
    $order_count_tkcg = OrderInfo::find()->where(['user_id' => $user_info->id, 'order_type' => 1, 'state' => 6])->count();
    $order_count_tksb = OrderInfo::find()->where(['user_id' => $user_info->id, 'order_type' => 1, 'state' => 7])->count();
    $order_count_yqx = OrderInfo::find()->where(['user_id' => $user_info->id, 'order_type' => 1, 'state' => 8])->count();
    $data = [
      'order_count_all' => (int)$order_count_all,
      'order_count_dzf' => (int)$order_count_dzf,
      'order_count_dfh' => (int)$order_count_dfh,
      'order_count_dsh' => (int)$order_count_dsh,
      'order_count_shz' => (int)$order_count_shz,
      'order_count_wc' => (int)$order_count_wc,
      'order_count_tkz' => (int)$order_count_tkz,
      'order_count_tkcg' => (int)$order_count_tkcg,
      'order_count_tksb' => (int)$order_count_tksb,
      'order_count_yqx' => (int)$order_count_yqx
    ]
    return Re::data(['data' => $data]);
  }

  //个人订单数据
  public function actionOrderList(){
    $openid = Yii::$app->request->post('openid', '');
    $state = Yii::$app->request->post('state', -1);
    $keyword = Yii::$app->request->post('keyword', '');
    $page = Yii::$app->request->post('page', 0);
    $page_size = Yii::$app->request->post('page_size', 10);
    $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
    if (!$user_info) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }
    $order_query = OrderInfo::find()
      ->leftJoin("order_info_good", "order_info.id = order_info_good.order_id")
      ->leftJoin("good", "order_info_good.good_id = good.id")
      ->where(['order_info.user_id' => $user_info->id, 'order_type' => 1]);
    if ($state > -1) {
      $order_query->andWhere(['order_info.state' => $state]);
    }
    if ($keyword) {
      $order_query->andWhere(['like', 'good.name', $keyword]);
    }
    $order_query->groupBy("order_info.id");
    $order_list = $order_query->orderBy("created_at desc")->limit($page_size)->offset($page_size*$page)->all();
    $order_data = [];
    if ($order_list) {
      foreach ($order_list as $v) {
        $good_list = OrderInfoGood::find()->where(['order_id' => $v->id])->all();
        $good_data = [];
        if ($good_list) {
          foreach ($good_list as $v1) {
            $good_data[] = [
              'good_id' => $v1->good_id,
              'good_name' => $v1->good->name,
              'good_img' => $v1->good->img,
              'good_price' => $v1->price,
              'num' => $v1->num
            ];
          }
        }
        $order_data[] = [
          'id' => $v->id,
          'order_sn' => $v->order_sn,
          'money' => $v->money,
          'pay_date' => $v->pay_at ? date('Y-m-d H:i:s', $v->pay_at) : '',
          'state' => $v->state,
          'state_name' => $this->state_arr[$v->state],
          'created_time' => date("Y-m-d H:i:s", $v->created_at),
          'good_list' => $good_data,
          'good_count' => count($good_data)
        ];
      }
    }
    return Re::data(['data' => $order_data]);
  }

  //订单详情
  public function actionOrderInfo(){
    $id = Yii::$app->request->post('id', '');
    $order_info = OrderInfo::findOne($id);
    if (!$order_info) {
      return Re::data(null, '订单信息读取错误', Re::ERROR);
    }
    $order_data = [];
    $good_list = OrderInfoGood::find()->where(['order_id' => $id])->all();

    $good_data = [];
    if ($good_list) {
      foreach ($good_list as $v) {
        $good_data[] = [
          'good_id' => $v->good_id,
          'good_name' => mb_strlen($v->good->name, 'UTF-8') >= 12 ? mb_substr($v->good->name, '0', 12, 'UTF-8') . '...' : $v->good->name,
          'good_img' => $v->good->img,
          'good_price' => $v->price,
          'num' => $v->num,
          'is_evaluate' => (int)OrderInfoGoodEvaluate::find()->where(['good_id' => $v->good_id, 'user_id' => $order_info->user_id])->exists()
        ];
      }
    }

    $order_data = [
      'id' => $order_info->id,
      'order_sn' => $order_info->order_sn,
      'money' => $order_info->money,
      'state' => $order_info->state,
      'state_name' => $this->state_arr[$order_info->state],
      'address_name' => $order_info->address->name,
      'address_phone' => $order_info->address->phone,
      'address' => $order_info->address->address,
      'remark' => $order_info->remark,
      'good_list' => $good_data,
      'order_send_code' => $order_info->order_send_code,
      'order_send_name' => $order_info->order_send_name,
      'created_time' => date("Y-m-d H:i:s", $order_info->created_at),
      'pay_time' => $order_info->pay_at ? date('Y-m-d H:i:s', $order_info->pay_at) : '',
      'send_time' => $order_info->send_at ? date('Y-m-d H:i:s', $order_info->send_at) : '',
      'receive_time' => $order_info->receive_at ? date('Y-m-d H:i:s', $order_info->receive_at) : '',
      'refund_start_time' => $order_info->refund_at ? date('Y-m-d H:i:s', $order_info->refund_start_at) : '',
      'refund_success_time' => $order_info->refund_at ? date('Y-m-d H:i:s', $order_info->refund_success_at) : '',
    ];
    return Re::data(['data' => $order_data]);
  }

  //确认收货
	public function actionOrderReceive() {
		$id = Yii::$app->request->post('id', 0);
    $order_info = OrderInfo::findOne($id);
    if (!$order_info) {
      return Re::data(null, '订单信息读取错误', Re::ERROR);
    }
		$order_info->state = 3;
		$order_info->receive_at = time();
    $order_info->save();
		return Re::data();
  }

  //添加订单评价
	public function actionOrderEvaluate() {
    $id = Yii::$app->request->post('id', 0);
    $openid = Yii::$app->request->post('openid', '');
    $good_id = Yii::$app->request->post('good_id', 0);
    $star = Yii::$app->request->post('star', 1);
    $video = Yii::$app->request->post('video', '');
    $imgs = Yii::$app->request->post('imgs', '');
    $content = Yii::$app->request->post('content', '');
    if (empty(empty($openid) || empty($id) || empty($good_id) || empty($content)) {
			return Re::data(null, '参数错误', Re::ERROR);
    }
    $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
    if (!$user_info) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }
    $order_info = OrderInfo::findOne($id);
    if (!$order_info) {
      return Re::data(null, '订单信息读取错误', Re::ERROR);
    }
    $order_info_good_evaluate = new OrderInfoGoodEvaluate();
    $order_info_good_evaluate->user_id = $user_info->id;
    $order_info_good_evaluate->order_id = $id;
    $order_info_good_evaluate->good_id = $good_id;
    $order_info_good_evaluate->star = $star;
    $order_info_good_evaluate->imgs = $imgs;
    $order_info_good_evaluate->video = $video;
    $order_info_good_evaluate->content = $content;
		$order_info_good_evaluate->created_at = time();
		$order_info_good_evaluate->save();
		return Re::data();
  }

  //申请退款
	public function actionOrderRefund() {
    $openid = Yii::$app->request->post('openid', '');
    $id = Yii::$app->request->post('id', 0);
    $good_id = Yii::$app->request->post('good_id', 0);
    $refund_reason = Yii::$app->request->post('refund_reason', '');
    $refund_imgs = Yii::$app->request->post('refund_imgs', '');
    if (empty($openid) || empty($id) || empty($good_id) || empty($refund_reason)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
    if (!$user_info) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }
    $order_info = OrderInfo::findOne($id);
    if (!$order_info) {
      return Re::data(null, '订单信息读取错误', Re::ERROR);
    }
  
		$orderRefund = new OrderInfo();
    $orderRefund->relate_id = $order_info->id;
    $orderRefund->order_type = 2;
		$orderRefund->user_id = $user_info->id;
		$orderRefund->order_sn = time().rand(1000,9999);
    $orderRefund->money = $order_info->money;
    $orderRefund->refund_state = 0;
    $orderRefund->refund_imgs = $refund_imgs;
    $orderRefund->refund_reason = $refund_reason;
    $orderRefund->remark = '商品退款';
		$orderRefund->created_at = time();
		$orderRefund->save();
    $order_info->state = 5;
		$order_info->refund_at = time();
		$order_info->save();
		return Re::data();
  }
  
  //订单取消
	public function actionOrderCancel() {
    $openid = Yii::$app->request->post('openid', '');
    $id = Yii::$app->request->post('id', 0);
    $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
    if (!$user_info) {
      return Re::data(null, '用户信息读取错误', Re::ERROR);
    }
    $order_info = OrderInfo::findOne($id);
    if (!$order_info) {
      return Re::data(null, '订单信息读取错误', Re::ERROR);
    }
    $order_info->state = 8;
    $order_info->save();
		return Re::data();
	}
}
